package com.class05.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import javax.sql.DataSource;

/**
 * @ClassDescription:
 * 持久层配置类：连接池、sqlSessionFactory，Mapper代理对象
 * @JdkVersion: 17
 * @Author: yxy
 * @Created: 2023/12/21 14:59
 * 方式1：保留外部配置文件
 * todo ：如果dataSource和mybatis的组件配置到一起，出现@Value注解不生效
 *   原因：mybatis的组件优先加载，@Value还没有读取！
 *   解决：分开配置，写到不同的类即可！
 */
@Configuration
public class MapperJavaConfig {
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean sqlSessionFactoryBean =
                new SqlSessionFactoryBean();
        //指定配置文件等信息
        //指定数据库莲池对象
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 指定外部的mybatis配置文件
        //spring.core
        ClassPathResource resource =
                new ClassPathResource("mybatis-config.xml");
        sqlSessionFactoryBean.setConfigLocation(resource);
        return sqlSessionFactoryBean;
    }

    //mapper代理对象加入到ioc
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        //Mapper代理对象的factoryBean->指定一个包->mapper接口->sqlSessionFactory->
        // ->sqlSession->getMapper->mapper代理对象->ioc
        MapperScannerConfigurer mapperScannerConfigurer =
                new MapperScannerConfigurer();
//        mapper接口和mapperxml所在共同包
        mapperScannerConfigurer.setBasePackage("com.class05.mapper");
        return mapperScannerConfigurer;
    }

}
